<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Validate;
class Medias extends BaseController {
    public function index() {
        $token = Request::header('Authorization');
        if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
            return json(['code' => 401, 'msg' => '未授权访问']);
        }
        $token = $matches[1];
        $user = Db::name('think_users')->where('token', $token)->find();
        if (!$user) {
            return json(['code' => 401, 'msg' => 'token无效']);
        }
        $list = Db::name('user_media_records')
            ->where('user_id', $user['id'])
            ->where('status', 1)
            ->order('create_time', 'desc')
            ->field([
                 'id',
                 'width',  // rename nickname to name
                 'height',  // rename avatar to poster
                 'media_url as url'
             ])
            ->select();
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $list]);
    }

    public function add() {
        $token = Request::header('Authorization');
        if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
            return json(['code' => 401, 'msg' => '未授权访问']);
        }
        $token = $matches[1];
        $user = Db::name('think_users')->where('token', $token)->find();
        if (!$user) {
            return json(['code' => 401, 'msg' => 'token无效']);
        }
        $pictures = Request::post('pictures', []);
        if (empty($pictures) || !is_array($pictures)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        foreach ($pictures as &$picture) {
            $picture["user_id"] = $user['id'];
        }
        Db::name('user_media_records')->insertAll($pictures);
        json(['code' => 200, 'msg' => '上传成功']);
    }

    public function delete() {
        $token = Request::header('Authorization');
        if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
            return json(['code' => 401, 'msg' => '未授权访问']);
        }
        $token = $matches[1];
        $user = Db::name('think_users')->where('token', $token)->find();
        if (!$user) {
            return json(['code' => 401, 'msg' => 'token无效']);
        }
        $id = Request::post('ids');
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        Db::name('user_media_records')->whereIn('id', $id)->where('user_id', $user['id'])->update(['status' => 0]);
        return json(['code' => 200, 'msg' => '删除成功']);
    }

    
}